package com.lian.pet.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lian.pet.common.basic.enums.DataTypeEnum;
import com.lian.pet.common.cache.redis.service.RedisService;
import com.lian.pet.domain.dto.AddVaccinesDTO;
import com.lian.pet.domain.dto.QueryVaccinesDTO;
import com.lian.pet.domain.entity.Pets;
import com.lian.pet.domain.entity.Vaccines;
import com.lian.pet.domain.vo.PetsVO;
import com.lian.pet.domain.vo.VaccinesVO;
import com.lian.pet.factory.ResponseBeanFactory;
import com.lian.pet.mapper.VaccinesMapper;
import com.lian.pet.service.VaccinesService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class VaccinesServiceImpl implements VaccinesService {
    private final RedisService redisService;
    private final VaccinesMapper vaccinesMapper;

    @Override
    public void addVaccines(AddVaccinesDTO req) {
        Vaccines vaccines = ResponseBeanFactory.getVaccines(req);
        vaccinesMapper.insert(vaccines);
        // 添加数据时 删除Cache数据
        redisService.delKey(DataTypeEnum.VACCINES.name());
        log.info("执行成功[新增疫苗]");
    }

    @Override
    public List<VaccinesVO> queryVaccines(QueryVaccinesDTO req, String name) {
        IPage<Vaccines> page = new Page<>(req.getPageNum(), req.getPageSize());
        IPage<Vaccines> iPage = vaccinesMapper.selectPage(page, Wrappers.<Vaccines>lambdaQuery()
                .eq(Vaccines::getName, name)
                .eq(StringUtils.isNotBlank(req.getName()), Vaccines::getName, req.getName()));
        List<Vaccines> vaccines = iPage.getRecords();
        if (vaccines.isEmpty()) {
            return Collections.emptyList();
        }
        List<VaccinesVO> vaccinesVOS = new ArrayList<>();
        vaccines.forEach(vaccine -> {
            VaccinesVO vaccinesVO = VaccinesVO.fromVaccines(vaccine);
            vaccinesVOS.add(vaccinesVO);
        });

        log.info("执行成功[查询疫苗列表]");
        return vaccinesVOS;
    }

    @Override
    public VaccinesVO getVaccines(Integer id) {
        Vaccines vaccines = vaccinesMapper.selectById(id);
        return VaccinesVO.fromVaccines(vaccines);
    }

    @Override
    public void deleteVaccines(Integer id) {
        vaccinesMapper.deleteById(id);
    }


}
